﻿using System;
using JamesZhao.Engine.Graphics.Effects;
using JamesZhao.Engine.Graphics.Surfaces;
using JamesZhao.Engine.Graphics.Visuals;
using SlimDX;
using SlimDX.Direct3D11;
using SlimDX.DXGI;

namespace JamesZhao.Engine.Graphics.RenderStages
{
    public class ViewspaceDepthStage : RenderStage
    {
        public DepthSurface DepthSurface { get; set; }
        public ColorSurface OutputDepth { get; set; }

        public ViewspaceDepthStage(GraphicsDevice device)
        {
            ViewspaceDepthEffect = new GpuProgram(device, "Shaders/ViewspaceDepth.fx");
        }

        protected GpuProgram ViewspaceDepthEffect { get; set; }

        public override string Name
        {
            get { return "ViewspaceDepth"; }
        }

        protected override void OnRender(GraphicsDevice device, SwapChain swapChain, VisualsList visualsList, Camera camera)
        {
            device.ImmediateContext.ClearRenderTargetView(OutputDepth.TargetView, new Color4(-1,-1,-1,-1));
            device.ImmediateContext.ClearDepthStencilView(DepthSurface.DepthView, DepthStencilClearFlags.Depth, 1, 0);

            device.ImmediateContext.OutputMerger.SetTargets(DepthSurface.DepthView,
                                                            new[]
                                                                {
                                                                    OutputDepth.TargetView
                                                                });

            ViewspaceDepthEffect.ScalarVariables["zFar"].Set(camera.Lens.Far);
            
            foreach (Drawable renderable in visualsList.Drawables)
            {
                renderable.RenderWithGpuProgram(device, camera, ViewspaceDepthEffect);
            }

        }
    }
}
